// store/modules/user.ts
import { StoreOptions } from "vuex";
import ACCESS_ENUM from "@/access/accessEnum";
import { UserControllerService } from "../../generated";

// 从本地存储初始化状态
const getInitialUserState = () => {
  const savedUser = localStorage.getItem("loginUser");
  return savedUser
    ? JSON.parse(savedUser)
    : {
        userName: "未登录",
        userRole: ACCESS_ENUM.NOT_LOGIN,
        userAvatar: "",
      };
};

export default {
  namespaced: true,
  state: () => ({
    loginUser: getInitialUserState(), // 初始化时读取本地存储
  }),
  actions: {
    async getLoginUser({ commit, state }) {
      try {
        const res = await UserControllerService.getLoginUserUsingGet();
        if (res.code === 0) {
          commit("updateUser", res.data);
          // 持久化到本地存储
          localStorage.setItem("loginUser", JSON.stringify(res.data));
        } else {
          throw new Error(res.message || "获取用户失败");
        }
      } catch (error) {
        commit("resetUser");
        console.error("获取用户信息失败:", error);
      }
    },
  },
  mutations: {
    updateUser(state, payload) {
      state.loginUser = payload;
    },
    resetUser(state) {
      state.loginUser = {
        userName: "未登录",
        userRole: ACCESS_ENUM.NOT_LOGIN,
        userAvatar: "",
      };
      localStorage.removeItem("loginUser");
    },
  },
  getters: {
    isLoggedIn: (state) => state.loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN,
  },
} as StoreOptions<any>;
